package com.cgwx.systemservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cgwx.systemservice.entity.sys.SysMenu;
import com.cgwx.systemservice.entity.sys.SysRoleMenu;
import com.cgwx.systemservice.entity.vo.AssginMenuVo;
import com.cgwx.systemservice.mapper.SysMenuMapper;
import com.cgwx.systemservice.mapper.SysRoleMenuMapper;
import com.cgwx.systemservice.service.SysRoleMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cgwx.systemservice.utils.MenuHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 角色菜单 服务实现类
 * </p>
 *
 * @author GaoWei
 * @since 2023-10-12
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements SysRoleMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

//    根据角色ID获取可操作的菜单列表将其选择状态设置为true；返回所有菜单列表
    @Override
    public List<SysMenu> findMenuByRoleId(Long roleId) {
//        获取所有菜单
        QueryWrapper<SysMenu> sysMenuQueryWrapper = new QueryWrapper<>();
        sysMenuQueryWrapper.eq("status",1);
        List<SysMenu> sysMenuList = sysMenuMapper.selectList(sysMenuQueryWrapper);
//        根据角色id查询角色分配的菜单列表
        QueryWrapper<SysRoleMenu> sysRoleMenuQueryWrapper = new QueryWrapper<>();
        sysRoleMenuQueryWrapper.eq("role_id",roleId);
        List<SysRoleMenu> sysRoleMenuList = baseMapper.selectList(sysRoleMenuQueryWrapper);
//        从列表中，获取当前角色所分配菜单的id
        List<Long> roleMenuIds = new ArrayList<>();
        for (SysRoleMenu sysRoleMenu : sysRoleMenuList) {
            roleMenuIds.add(sysRoleMenu.getMenuId());
        }
//        数据处理：isSelected 如果选中了 true；没选中false
        for (SysMenu sysMenu : sysMenuList) {
//            遍历所有菜单，看看是否是当前角色所分配的菜单，设置isSelected值（所有菜单都需要设置）
            if (roleMenuIds.contains(sysMenu.getId())) {
                sysMenu.setSelect(true);
            }else{
                sysMenu.setSelect(false);
            }
        }
//        转换为tree结构
        return MenuHelper.buildTree(sysMenuList);
    }

//    给角色分配菜单权限
    @Override
    public void doAssign(AssginMenuVo assginMenuVo) {
//        根据角色ID删除菜单权限
        QueryWrapper<SysRoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id",assginMenuVo.getRoleId());
        baseMapper.delete(queryWrapper);
//        添加菜单列表
        List<Long> menuIdList = assginMenuVo.getMenuIdList();
        for (Long menuId : menuIdList) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setMenuId(menuId);
            sysRoleMenu.setRoleId(assginMenuVo.getRoleId());
            baseMapper.insert(sysRoleMenu);
        }
    }
}
